#include "widget.h"
#include <QGroupBox>
#include <QFormLayout>
#include <QScrollBar>
#include <QFileInfo>
#include <QDir>
#include <QTimer>

ConfigTool::ConfigTool(QWidget *parent)
    : QMainWindow(parent), m_resultWindow(nullptr)
{
    // 从设置中加载上次的路径
    QSettings settings;
    m_lastImageDir = settings.value("lastImageDir", QDir::currentPath()).toString();
    m_lastConfigDir = settings.value("lastConfigDir", QDir::currentPath()).toString();
    m_lastSaveDir = settings.value("lastSaveDir", QDir::currentPath()).toString();

    initMainWindow();

    // 程序启动后自动扫描configs目录
    QTimer::singleShot(100, this, &ConfigTool::scanConfigsDirectory);
}

ConfigTool::~ConfigTool()
{
}

void ConfigTool::initMainWindow()
{
    setWindowTitle("配置文件工具（多配置融合）");
    setGeometry(100, 100, 1000, 750);

    // 主部件
    m_centralWidget = new QWidget(this);
    setCentralWidget(m_centralWidget);
    m_mainLayout = new QVBoxLayout(m_centralWidget);

    // 1. 说明文本
    QLabel *infoLabel = new QLabel("支持加载多个外部配置文件，与图片配置融合生成完整配置（后加载的配置会覆盖同名字段）", this);
    infoLabel->setAlignment(Qt::AlignCenter);
    infoLabel->setStyleSheet("font-size: 14px; margin: 10px 0;");
    m_mainLayout->addWidget(infoLabel);

    // 2. 核心功能按钮区
    QHBoxLayout *coreBtnLayout = new QHBoxLayout();
    coreBtnLayout->setSpacing(15);
    coreBtnLayout->setContentsMargins(20, 0, 20, 0);

    // 选择图片按钮组
    QHBoxLayout *selectBtnLayout = new QHBoxLayout();
    selectBtnLayout->setSpacing(15);

    QPushButton *mainBtn = new QPushButton("选择主图", this);
    mainBtn->setStyleSheet("padding: 8px 16px; font-size: 14px;");
    connect(mainBtn, &QPushButton::clicked, this, &ConfigTool::selectMainImages);

    QPushButton *detailBtn = new QPushButton("选择详情图", this);
    detailBtn->setStyleSheet("padding: 8px 16px; font-size: 14px;");
    connect(detailBtn, &QPushButton::clicked, this, &ConfigTool::selectDetailImages);

    QPushButton *skuBtn = new QPushButton("选择SKU图", this);
    skuBtn->setStyleSheet("padding: 8px 16px; font-size: 14px;");
    connect(skuBtn, &QPushButton::clicked, this, &ConfigTool::selectSkuImages);

    selectBtnLayout->addWidget(mainBtn);
    selectBtnLayout->addWidget(detailBtn);
    selectBtnLayout->addWidget(skuBtn);

    // 配置操作按钮组
    QHBoxLayout *configBtnLayout = new QHBoxLayout();
    configBtnLayout->setSpacing(10);

    // 扫描配置按钮
    QPushButton *scanBtn = new QPushButton("扫描配置", this);
    scanBtn->setStyleSheet("padding: 8px 16px; font-size: 14px; background-color: #FF9800; color: white;");
    connect(scanBtn, &QPushButton::clicked, this, &ConfigTool::scanConfigsDirectory);

    // 添加外部配置按钮
    QPushButton *addBtn = new QPushButton("添加配置", this);
    addBtn->setStyleSheet("padding: 8px 16px; font-size: 14px; background-color: #2196F3; color: white;");
    connect(addBtn, &QPushButton::clicked, this, &ConfigTool::loadExternalConfigs);

    // 全选/取消全选按钮
    m_selectAllBtn = new QPushButton("全选", this);
    m_selectAllBtn->setStyleSheet("padding: 8px 12px; font-size: 12px;");
    connect(m_selectAllBtn, &QPushButton::clicked, this, &ConfigTool::selectAllConfigs);

    m_deselectAllBtn = new QPushButton("取消全选", this);
    m_deselectAllBtn->setStyleSheet("padding: 8px 12px; font-size: 12px;");
    connect(m_deselectAllBtn, &QPushButton::clicked, this, &ConfigTool::deselectAllConfigs);

    // 移除选中配置按钮
    QPushButton *removeBtn = new QPushButton("移除选中", this);
    removeBtn->setStyleSheet("padding: 8px 16px; font-size: 14px; background-color: #f44336; color: white;");
    connect(removeBtn, &QPushButton::clicked, this, &ConfigTool::removeSelectedConfig);

    // 保存融合配置按钮
    QPushButton *saveBtn = new QPushButton("保存融合", this);
    saveBtn->setStyleSheet("padding: 8px 16px; font-size: 14px; background-color: #4CAF50; color: white;");
    connect(saveBtn, &QPushButton::clicked, this, &ConfigTool::saveMergedConfig);

    configBtnLayout->addWidget(scanBtn);
    configBtnLayout->addWidget(addBtn);
    configBtnLayout->addWidget(m_selectAllBtn);
    configBtnLayout->addWidget(m_deselectAllBtn);
    configBtnLayout->addWidget(removeBtn);
    configBtnLayout->addWidget(saveBtn);

    coreBtnLayout->addLayout(selectBtnLayout);
    coreBtnLayout->addLayout(configBtnLayout);
    m_mainLayout->addLayout(coreBtnLayout);

    // 3. 配置预览区域
    QFrame *previewFrame = new QFrame(this);
    previewFrame->setFrameShape(QFrame::StyledPanel);
    previewFrame->setStyleSheet("margin: 10px 20px; padding: 10px;");
    QVBoxLayout *previewLayout = new QVBoxLayout(previewFrame);

    QLabel *previewLabel = new QLabel("配置预览：", this);
    previewLabel->setStyleSheet("font-weight: bold; margin-bottom: 5px;");
    previewLayout->addWidget(previewLabel);

    // 水平分割
    QSplitter *hSplitter = new QSplitter(Qt::Horizontal, this);

    // 左侧配置面板
    QWidget *leftPanel = new QWidget(this);
    leftPanel->setMaximumWidth(300);
    QVBoxLayout *leftLayout = new QVBoxLayout(leftPanel);

    // 扫描状态标签
    m_scanStatus = new QLabel("准备扫描配置...", this);
    m_scanStatus->setStyleSheet("color: #666; padding: 5px; background-color: #f0f0f0; border-radius: 3px;");
    m_scanStatus->setAlignment(Qt::AlignCenter);
    leftLayout->addWidget(m_scanStatus);

    // 配置复选框列表
    m_configCheckList = new QListWidget(this);
    m_configCheckList->setSelectionMode(QListWidget::ExtendedSelection);
    connect(m_configCheckList, &QListWidget::itemClicked, this, &ConfigTool::showSelectedConfig);
    connect(m_configCheckList, &QListWidget::itemChanged, this, &ConfigTool::updateConfigSelection);
    leftLayout->addWidget(m_configCheckList);

    hSplitter->addWidget(leftPanel);

    // 右侧垂直分割
    QSplitter *vSplitter = new QSplitter(Qt::Vertical, this);

    // 上部分：图片配置
    m_imageConfigText = new QTextEdit(this);
    m_imageConfigText->setReadOnly(true);
    m_imageConfigText->setFont(QFont("Consolas", 10));
    m_imageConfigText->setStyleSheet("background-color: #f5f5f5;");
    m_imageConfigText->setPlaceholderText("图片配置将显示在这里...");
    vSplitter->addWidget(m_imageConfigText);

    // 下部分：外部配置
    QWidget *externalFrame = new QWidget(this);
    QVBoxLayout *externalLayout = new QVBoxLayout(externalFrame);

    m_externalConfigText = new QTextEdit(this);
    m_externalConfigText->setReadOnly(true);
    m_externalConfigText->setFont(QFont("Consolas", 10));
    m_externalConfigText->setStyleSheet("background-color: #f0f8ff;");
    m_externalConfigText->setPlaceholderText("请从左侧选择配置文件查看详情...");
    externalLayout->addWidget(m_externalConfigText);

    QLabel *mergeHint = new QLabel("<font color='blue'>提示：保存时将融合所有选中的配置（后加载的覆盖先加载的同名字段）</font>", this);
    mergeHint->setAlignment(Qt::AlignCenter);
    mergeHint->setStyleSheet("margin-top: 5px;");
    externalLayout->addWidget(mergeHint);

    vSplitter->addWidget(externalFrame);
    vSplitter->setSizes({300, 200});
    hSplitter->addWidget(vSplitter);

    // 设置分割比例
    hSplitter->setSizes({250, 650});
    previewLayout->addWidget(hSplitter);

    m_mainLayout->addWidget(previewFrame);

    // 4. 状态区域
    QFrame *statusFrame = new QFrame(this);
    statusFrame->setFrameShape(QFrame::StyledPanel);
    statusFrame->setStyleSheet("margin: 10px 20px; padding: 10px;");
    QHBoxLayout *statusLayout = new QHBoxLayout(statusFrame);

    m_mainStatus = new QLabel("主图：未选择任何文件", this);
    m_detailStatus = new QLabel("详情图：未选择任何文件", this);
    m_skuStatus = new QLabel("SKU图：未选择任何文件", this);
    m_externalStatus = new QLabel("外部配置：0个", this);

    m_mainStatus->setStyleSheet("color: gray; margin-right: 20px;");
    m_detailStatus->setStyleSheet("color: gray; margin-right: 20px;");
    m_skuStatus->setStyleSheet("color: gray; margin-right: 20px;");
    m_externalStatus->setStyleSheet("color: #2196F3;");

    statusLayout->addWidget(m_mainStatus);
    statusLayout->addWidget(m_detailStatus);
    statusLayout->addWidget(m_skuStatus);
    statusLayout->addWidget(m_externalStatus);
    statusLayout->addStretch();

    m_mainLayout->addWidget(statusFrame);
    m_mainLayout->addStretch();

    updateConfigText();
}

void ConfigTool::selectMainImages()
{
    QString initialDir = m_lastImageDir.isEmpty() ? QDir::currentPath() : m_lastImageDir;

    QStringList files = QFileDialog::getOpenFileNames(this, "选择主图文件",
                                                      initialDir,
                                                      "图片文件 (*.jpg *.jpeg *.png *.bmp *.gif);;所有文件 (*.*)");
    if (!files.isEmpty()) {
        m_mainImages = files;
        m_mainStatus->setText(QString("主图：已选择 %1 个文件").arg(files.size()));
        m_mainStatus->setStyleSheet("color: green; margin-right: 20px;");
        m_currentImgType = "main";

        // 更新图片目录记忆
        m_lastImageDir = QFileInfo(files.first()).absolutePath();
        QSettings settings;
        settings.setValue("lastImageDir", m_lastImageDir);

        showImageTable("主图", m_mainImages);
        updateConfigText();
    }
}

void ConfigTool::selectDetailImages()
{
    QString initialDir = m_lastImageDir.isEmpty() ? QDir::currentPath() : m_lastImageDir;

    QStringList files = QFileDialog::getOpenFileNames(this, "选择详情图文件",
                                                      initialDir,
                                                      "图片文件 (*.jpg *.jpeg *.png *.bmp *.gif);;所有文件 (*.*)");
    if (!files.isEmpty()) {
        m_detailImages = files;
        m_detailStatus->setText(QString("详情图：已选择 %1 个文件").arg(files.size()));
        m_detailStatus->setStyleSheet("color: blue; margin-right: 20px;");
        m_currentImgType = "detail";

        // 更新图片目录记忆
        m_lastImageDir = QFileInfo(files.first()).absolutePath();
        QSettings settings;
        settings.setValue("lastImageDir", m_lastImageDir);

        showImageTable("详情图", m_detailImages);
        updateConfigText();
    }
}

void ConfigTool::selectSkuImages()
{
    QString initialDir = m_lastImageDir.isEmpty() ? QDir::currentPath() : m_lastImageDir;

    QStringList files = QFileDialog::getOpenFileNames(this, "选择SKU图文件",
                                                      initialDir,
                                                      "图片文件 (*.jpg *.jpeg *.png *.bmp *.gif);;所有文件 (*.*)");
    if (!files.isEmpty()) {
        m_skuData.clear();
        for (const QString &file : files) {
            m_skuData.append({file, "", ""});
        }
        m_skuStatus->setText(QString("SKU图：已选择 %1 个文件").arg(files.size()));
        m_skuStatus->setStyleSheet("color: purple; margin-right: 20px;");
        m_currentImgType = "sku";

        // 更新图片目录记忆
        m_lastImageDir = QFileInfo(files.first()).absolutePath();
        QSettings settings;
        settings.setValue("lastImageDir", m_lastImageDir);

        showImageTable("SKU图", QVariant::fromValue(m_skuData));
        updateConfigText();
    }
}

void ConfigTool::scanConfigsDirectory()
{
    m_scanStatus->setText("正在扫描 configs 目录...");

    // 清空当前列表但保留选中状态（如果需要的话）
    m_configCheckList->clear();
    m_externalConfigs.clear();

    // 检查configs目录是否存在
    QDir configDir("configs");
    if (!configDir.exists()) {
        m_scanStatus->setText("configs 目录不存在");
        QMessageBox::information(this, "目录不存在",
                                 "configs 目录不存在，将自动创建该目录。\n您可以将JSON配置文件放入此目录。");

        // 创建configs目录
        if (configDir.mkpath(".")) {
            m_scanStatus->setText("已创建 configs 目录");
        } else {
            m_scanStatus->setText("无法创建 configs 目录");
        }
        return;
    }

    // 扫描JSON文件
    QStringList jsonFilters;
    jsonFilters << "*.json";
    QFileInfoList jsonFiles = configDir.entryInfoList(jsonFilters, QDir::Files);

    if (jsonFiles.isEmpty()) {
        m_scanStatus->setText("configs 目录中没有找到JSON文件");
        return;
    }

    int loadedCount = 0;
    for (const QFileInfo &fileInfo : jsonFiles) {
        QFile file(fileInfo.absoluteFilePath());
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            continue;
        }

        QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
        file.close();

        if (doc.isNull()) {
            continue;
        }

        // 添加到配置列表
        QString fileName = fileInfo.fileName();
        m_externalConfigs.append(qMakePair(fileName, doc.object()));

        // 添加到复选框列表
        QListWidgetItem *item = new QListWidgetItem(fileName);
        item->setCheckState(Qt::Unchecked); // 默认选中
        item->setData(Qt::UserRole, m_externalConfigs.size() - 1); // 存储索引
        item->setToolTip(fileInfo.absoluteFilePath());
        m_configCheckList->addItem(item);

        loadedCount++;
    }

    m_scanStatus->setText(QString("找到 %1 个配置文件").arg(loadedCount));
    m_externalStatus->setText(QString("外部配置：%1个").arg(m_externalConfigs.size()));

    // 自动选择第一个配置显示详情
    if (m_configCheckList->count() > 0) {
        m_configCheckList->setCurrentRow(0);
        showSelectedConfig(m_configCheckList->item(0));
    }
}

void ConfigTool::loadExternalConfigs()
{
    QString initialDir = m_lastConfigDir.isEmpty() ? QDir::currentPath() : m_lastConfigDir;

    QStringList filePaths = QFileDialog::getOpenFileNames(this, "添加配置文件",
                                                          initialDir,
                                                          "JSON文件 (*.json);;所有文件 (*.*)");
    if (filePaths.isEmpty()) return;

    // 更新配置目录记忆
    m_lastConfigDir = QFileInfo(filePaths.first()).absolutePath();
    QSettings settings;
    settings.setValue("lastConfigDir", m_lastConfigDir);

    int addedCount = 0;
    for (const QString &filePath : filePaths) {
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QMessageBox::warning(this, "加载失败",
                                 QString("文件 %1 无法打开").arg(QFileInfo(filePath).fileName()));
            continue;
        }

        QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
        file.close();

        if (doc.isNull()) {
            QMessageBox::warning(this, "加载失败",
                                 QString("文件 %1 不是有效的JSON").arg(QFileInfo(filePath).fileName()));
            continue;
        }

        QString fileName = QFileInfo(filePath).fileName();

        // 检查是否已存在同名配置
        bool exists = false;
        for (int i = 0; i < m_configCheckList->count(); ++i) {
            if (m_configCheckList->item(i)->text() == fileName) {
                exists = true;
                break;
            }
        }

        if (exists) {
            int ret = QMessageBox::question(this, "文件已存在",
                                            QString("配置文件 '%1' 已存在，是否替换？").arg(fileName),
                                            QMessageBox::Yes | QMessageBox::No);
            if (ret == QMessageBox::No) {
                continue;
            }
            // 替换逻辑需要额外实现，这里简化为跳过
            continue;
        }

        m_externalConfigs.append(qMakePair(fileName, doc.object()));

        QListWidgetItem *item = new QListWidgetItem(fileName);
        item->setCheckState(Qt::Unchecked);
        item->setData(Qt::UserRole, m_externalConfigs.size() - 1);
        item->setToolTip(filePath);
        m_configCheckList->addItem(item);
        addedCount++;
    }

    m_externalStatus->setText(QString("外部配置：%1个").arg(m_externalConfigs.size()));

    if (addedCount > 0) {
        QMessageBox::information(this, "添加成功",
                                 QString("成功添加 %1 个配置文件").arg(addedCount));
    }
}

void ConfigTool::removeSelectedConfig()
{
    QList<QListWidgetItem*> selectedItems = m_configCheckList->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::warning(this, "提示", "请选择要移除的配置");
        return;
    }

    // 由于删除会影响索引，我们需要先收集要删除的配置索引
    QList<int> indicesToRemove;
    for (QListWidgetItem *item : selectedItems) {
        int index = item->data(Qt::UserRole).toInt();
        indicesToRemove.append(index);
    }

    // 按从大到小排序，这样删除时不会影响前面的索引
    std::sort(indicesToRemove.begin(), indicesToRemove.end(), std::greater<int>());

    // 从数据列表中移除
    for (int index : indicesToRemove) {
        if (index >= 0 && index < m_externalConfigs.size()) {
            m_externalConfigs.removeAt(index);
        }
    }

    // 从列表控件中移除
    for (QListWidgetItem *item : selectedItems) {
        delete m_configCheckList->takeItem(m_configCheckList->row(item));
    }

    // 重新设置所有项的索引
    for (int i = 0; i < m_configCheckList->count(); ++i) {
        QListWidgetItem *item = m_configCheckList->item(i);
        item->setData(Qt::UserRole, i);
    }

    m_externalStatus->setText(QString("外部配置：%1个").arg(m_externalConfigs.size()));
    m_externalConfigText->clear();
    m_externalConfigText->setPlaceholderText("请从左侧选择配置文件查看详情...");
}

void ConfigTool::saveMergedConfig()
{
    // 构建图片配置（这部分原代码不变，直接保留）
    QJsonObject imageConfig;
    QJsonArray mainArray, detailArray, skuArray;

    for (const QString &path : m_mainImages) {
        mainArray.append(path);
    }

    for (const QString &path : m_detailImages) {
        detailArray.append(path);
    }

    for (const QList<QVariant> &sku : m_skuData) {
        QJsonObject skuObj;
        skuObj["path"] = sku[0].toString();
        skuObj["price"] = sku[1].toString();
        skuObj["code"] = sku[2].toString();
        skuArray.append(skuObj);
    }

    imageConfig["main_images"] = mainArray;
    imageConfig["detail_images"] = detailArray;
    imageConfig["sku_images"] = skuArray;

    // 只融合选中的外部配置（===== 从这里开始修改 =====）
    QJsonObject mergedConfig = imageConfig;

    int selectedCount = 0;
    for (int i = 0; i < m_configCheckList->count(); ++i) {
        QListWidgetItem *item = m_configCheckList->item(i);
        if (item->checkState() == Qt::Checked) {
            int index = item->data(Qt::UserRole).toInt();
            if (index >= 0 && index < m_externalConfigs.size()) {
                QJsonObject externalObj = m_externalConfigs[index].second;
                // 遍历外部配置的每个字段
                for (auto it = externalObj.begin(); it != externalObj.end(); ++it) {
                    QString key = it.key();
                    // 1. 如果是三个图片字段：执行追加逻辑
                    if (key == "main_images" || key == "detail_images" || key == "sku_images") {
                        // 先获取本地已有的数组
                        QJsonArray localArray = mergedConfig.value(key).toArray();
                        // 获取外部配置的数组
                        QJsonArray externalArray = it.value().toArray();
                        // 把外部数组的元素逐个追加到本地数组后面
                        for (const QJsonValue &val : externalArray) {
                            localArray.append(val);
                        }
                        // 更新回融合配置
                        mergedConfig[key] = localArray;
                    }
                    // 2. 非图片字段：保持原逻辑（外部覆盖本地）
                    else {
                        mergedConfig[key] = it.value();
                    }
                }
                selectedCount++;
            }
        }
    }

    // 以下「添加元数据」「保存文件」的代码完全不变，直接保留
    mergedConfig["save_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    QJsonArray mergedFiles;
    for (int i = 0; i < m_configCheckList->count(); ++i) {
        QListWidgetItem *item = m_configCheckList->item(i);
        if (item->checkState() == Qt::Unchecked) continue;

        int index = item->data(Qt::UserRole).toInt();
        if (index >= 0 && index < m_externalConfigs.size()) {
            mergedFiles.append(m_externalConfigs[index].first);
        }
    }
    mergedConfig["merged_files"] = mergedFiles;

    // 保存文件
    QString currentDate = QDateTime::currentDateTime().date().toString("yyyyMMdd");
    QString defaultFilename = QString("merged_config_%1.json").arg(currentDate);

    QString initialDir = m_lastSaveDir.isEmpty() ? QDir::currentPath() : m_lastSaveDir;
    QString filePath = QFileDialog::getSaveFileName(this, "保存融合配置",
                                                    initialDir + "/" + defaultFilename,
                                                    "JSON文件 (*.json);;所有文件 (*.*)");

    if (filePath.isEmpty()) return;

    // 更新保存目录记忆
    m_lastSaveDir = QFileInfo(filePath).absolutePath();
    QSettings settings;
    settings.setValue("lastSaveDir", m_lastSaveDir);

    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "保存失败", "无法创建文件");
        return;
    }

    QJsonDocument doc(mergedConfig);
    file.write(doc.toJson());
    file.close();

    QString msg = QString("配置已成功保存到：\n%1\n\n融合内容：\n- 图片配置（主图%2张，详情图%3张，SKU图%4张）\n- 外部配置（共%5个文件，选中%6个）")
                      .arg(filePath).arg(m_mainImages.size()).arg(m_detailImages.size())
                      .arg(m_skuData.size()).arg(m_externalConfigs.size()).arg(selectedCount);

    QMessageBox::information(this, "保存成功", msg);
}

void ConfigTool::showSelectedConfig(QListWidgetItem *item)
{
    if (!item) return;

    int index = item->data(Qt::UserRole).toInt();
    if (index >= 0 && index < m_externalConfigs.size()) {
        QJsonDocument doc(m_externalConfigs[index].second);
        m_externalConfigText->setText(doc.toJson());
    }
}

void ConfigTool::updateConfigSelection()
{
    // 更新选中配置的显示
    QListWidgetItem *currentItem = m_configCheckList->currentItem();
    if (currentItem) {
        showSelectedConfig(currentItem);
    }
}

void ConfigTool::selectAllConfigs()
{
    for (int i = 0; i < m_configCheckList->count(); ++i) {
        QListWidgetItem *item = m_configCheckList->item(i);
        item->setCheckState(Qt::Checked);
    }
}

void ConfigTool::deselectAllConfigs()
{
    for (int i = 0; i < m_configCheckList->count(); ++i) {
        QListWidgetItem *item = m_configCheckList->item(i);
        item->setCheckState(Qt::Unchecked);
    }
}

void ConfigTool::showImageTable(const QString &title, const QVariant &displayData)
{
    m_resultWindow = new QMainWindow(this);
    m_resultWindow->setWindowTitle(title + "列表");
    m_resultWindow->setGeometry(200, 200, 1200, 600);

    QWidget *centralWidget = new QWidget(m_resultWindow);
    m_resultWindow->setCentralWidget(centralWidget);
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    // 标题
    int count = 0;
    if (m_currentImgType == "sku") {
        count = m_skuData.size();
    } else if (m_currentImgType == "main") {
        count = m_mainImages.size();
    } else {
        count = m_detailImages.size();
    }

    QString titleText = title + QString(" - 共 %1 个文件").arg(count);
    if (m_currentImgType == "sku") {
        titleText += " | 支持批量选择和批量设置";
    }

    QLabel *titleLabel = new QLabel(titleText, m_resultWindow);
    titleLabel->setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px 0;");
    mainLayout->addWidget(titleLabel);

    // SKU功能区
    if (m_currentImgType == "sku") {
        QFrame *functionFrame = new QFrame(m_resultWindow);
        functionFrame->setFrameShape(QFrame::StyledPanel);
        functionFrame->setStyleSheet("padding: 10px; margin-bottom: 10px;");
        QHBoxLayout *functionLayout = new QHBoxLayout(functionFrame);
        functionLayout->setSpacing(20);

        // 搜索区
        QFrame *searchFrame = new QFrame(m_resultWindow);
        QHBoxLayout *searchLayout = new QHBoxLayout(searchFrame);
        searchLayout->setContentsMargins(0, 0, 0, 0);

        QLabel *searchLabel = new QLabel("搜索文件名：", m_resultWindow);
        m_searchInput = new QLineEdit(m_resultWindow);
        m_searchInput->setPlaceholderText("输入关键词过滤（如：加绒）");
        m_searchInput->setMinimumWidth(200);
        connect(m_searchInput, &QLineEdit::textChanged, this, &ConfigTool::filterSkuItems);

        searchLayout->addWidget(searchLabel);
        searchLayout->addWidget(m_searchInput);
        functionLayout->addWidget(searchFrame);

        // 分隔线
        QFrame *line = new QFrame(m_resultWindow);
        line->setFrameShape(QFrame::VLine);
        line->setFrameShadow(QFrame::Sunken);
        functionLayout->addWidget(line);

        // 批量设置区
        QFrame *batchFrame = new QFrame(m_resultWindow);
        QHBoxLayout *batchLayout = new QHBoxLayout(batchFrame);
        batchLayout->setContentsMargins(0, 0, 0, 0);
        batchLayout->setSpacing(10);

        QLabel *priceLabel = new QLabel("批量设置价格：", m_resultWindow);
        m_batchPrice = new QLineEdit(m_resultWindow);
        m_batchPrice->setMaximumWidth(100);
        QPushButton *batchPriceBtn = new QPushButton("应用", m_resultWindow);
        connect(batchPriceBtn, &QPushButton::clicked, this, &ConfigTool::batchUpdatePrice);

        QLabel *codeLabel = new QLabel("批量设置编码：", m_resultWindow);
        m_batchCode = new QLineEdit(m_resultWindow);
        m_batchCode->setMaximumWidth(150);
        QPushButton *batchCodeBtn = new QPushButton("应用", m_resultWindow);
        connect(batchCodeBtn, &QPushButton::clicked, this, &ConfigTool::batchUpdateCode);

        batchLayout->addWidget(priceLabel);
        batchLayout->addWidget(m_batchPrice);
        batchLayout->addWidget(batchPriceBtn);
        batchLayout->addSpacing(20);
        batchLayout->addWidget(codeLabel);
        batchLayout->addWidget(m_batchCode);
        batchLayout->addWidget(batchCodeBtn);

        functionLayout->addWidget(batchFrame);
        functionLayout->addStretch();
        mainLayout->addWidget(functionFrame);
    }

    // 创建表格
    int colCount = (m_currentImgType == "sku") ? 5 : 3;
    m_table = new QTableWidget(count, colCount, m_resultWindow);

    if (m_currentImgType == "sku") {
        m_table->setSelectionMode(QTableWidget::ExtendedSelection);
        m_table->setSelectionBehavior(QTableWidget::SelectRows);
        connect(m_table, &QTableWidget::itemChanged, this, &ConfigTool::onSkuItemChanged);
    }

    // 设置表头
    if (m_currentImgType == "sku") {
        m_table->setHorizontalHeaderLabels({"缩略图", "序号", "文件路径", "价格", "商家编码"});
        m_table->setColumnWidth(0, 80);
        m_table->setColumnWidth(1, 60);
        m_table->setColumnWidth(3, 100);
        m_table->setColumnWidth(4, 150);
    } else {
        m_table->setHorizontalHeaderLabels({"缩略图", "序号", "文件路径"});
        m_table->setColumnWidth(0, 80);
        m_table->setColumnWidth(1, 60);
    }

    m_table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch);
    m_table->verticalHeader()->setDefaultSectionSize(60);

    fillTableData(displayData);
    mainLayout->addWidget(m_table);

    // 关闭按钮
    QPushButton *closeBtn = new QPushButton("关闭", m_resultWindow);
    closeBtn->setStyleSheet("padding: 8px; margin: 10px;");
    connect(closeBtn, &QPushButton::clicked, m_resultWindow, &QMainWindow::close);
    mainLayout->addWidget(closeBtn, 0, Qt::AlignCenter);

    m_resultWindow->show();
}

void ConfigTool::fillTableData(const QVariant &displayData, const QList<int> &filteredRows)
{
    m_table->clearContents();

    int rowCount = 0;
    if (m_currentImgType == "sku") {
        rowCount = m_skuData.size();
    } else if (m_currentImgType == "main") {
        rowCount = m_mainImages.size();
    } else {
        rowCount = m_detailImages.size();
    }

    m_table->setRowCount(rowCount);
    m_visibleRows.clear();

    for (int row = 0; row < rowCount; ++row) {
        if (!filteredRows.isEmpty() && !filteredRows.contains(row)) {
            m_table->setRowHidden(row, true);
            continue;
        }

        m_table->setRowHidden(row, false);
        m_visibleRows.append(row);

        // 获取文件路径
        QString filePath;
        if (m_currentImgType == "sku") {
            filePath = m_skuData[row][0].toString();
        } else if (m_currentImgType == "main") {
            filePath = m_mainImages[row];
        } else {
            filePath = m_detailImages[row];
        }

        // 缩略图
        QWidget *thumbWidget = new QWidget();
        QHBoxLayout *thumbLayout = new QHBoxLayout(thumbWidget);
        thumbLayout->setContentsMargins(5, 5, 5, 5);

        QLabel *thumbLabel = new QLabel();
        QPixmap pixmap(filePath);
        if (!pixmap.isNull()) {
            pixmap = pixmap.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            thumbLabel->setPixmap(pixmap);
        } else {
            thumbLabel->setText("无法预览");
        }
        thumbLayout->addWidget(thumbLabel, 0, Qt::AlignCenter);
        m_table->setCellWidget(row, 0, thumbWidget);

        // 序号
        QTableWidgetItem *indexItem = new QTableWidgetItem(QString::number(row + 1));
        indexItem->setTextAlignment(Qt::AlignCenter);
        indexItem->setFlags(indexItem->flags() & ~Qt::ItemIsEditable);
        m_table->setItem(row, 1, indexItem);

        // 文件路径
        QTableWidgetItem *pathItem = new QTableWidgetItem(filePath);
        pathItem->setToolTip(filePath);
        pathItem->setFlags(pathItem->flags() & ~Qt::ItemIsEditable);
        m_table->setItem(row, 2, pathItem);

        // SKU特殊列
        if (m_currentImgType == "sku") {
            QTableWidgetItem *priceItem = new QTableWidgetItem(m_skuData[row][1].toString());
            priceItem->setTextAlignment(Qt::AlignCenter);
            m_table->setItem(row, 3, priceItem);

            QTableWidgetItem *codeItem = new QTableWidgetItem(m_skuData[row][2].toString());
            codeItem->setTextAlignment(Qt::AlignCenter);
            m_table->setItem(row, 4, codeItem);
        }
    }
}

void ConfigTool::filterSkuItems()
{
    if (m_currentImgType != "sku") return;

    QString keyword = m_searchInput->text().toLower();
    if (keyword.isEmpty()) {
        fillTableData(QVariant::fromValue(m_skuData));
        return;
    }

    QList<int> filteredRows;
    for (int row = 0; row < m_skuData.size(); ++row) {
        QString fileName = QFileInfo(m_skuData[row][0].toString()).fileName().toLower();
        if (fileName.contains(keyword)) {
            filteredRows.append(row);
        }
    }

    fillTableData(QVariant::fromValue(m_skuData), filteredRows);
    QMessageBox::information(m_resultWindow, "筛选结果",
                             QString("找到 %1 个包含 '%2' 的文件").arg(filteredRows.size()).arg(keyword));
}

void ConfigTool::batchUpdatePrice()
{
    if (m_currentImgType != "sku") return;

    QList<QTableWidgetItem*> selectedItems = m_table->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::warning(m_resultWindow, "提示", "请先选择要更新的项（可按住Ctrl/Shift批量选择）");
        return;
    }

    QSet<int> selectedRows;
    for (QTableWidgetItem *item : selectedItems) {
        selectedRows.insert(item->row());
    }

    QString value = m_batchPrice->text();
    for (int row : selectedRows) {
        if (m_visibleRows.contains(row)) {
            m_skuData[row][1] = value;
            m_table->item(row, 3)->setText(value);
        }
    }

    updateConfigText();
    QMessageBox::information(m_resultWindow, "更新成功",
                             QString("已为 %1 个选中项更新价格").arg(selectedRows.size()));
}

void ConfigTool::batchUpdateCode()
{
    if (m_currentImgType != "sku") return;

    QList<QTableWidgetItem*> selectedItems = m_table->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::warning(m_resultWindow, "提示", "请先选择要更新的项（可按住Ctrl/Shift批量选择）");
        return;
    }

    QSet<int> selectedRows;
    for (QTableWidgetItem *item : selectedItems) {
        selectedRows.insert(item->row());
    }

    QString value = m_batchCode->text();
    for (int row : selectedRows) {
        if (m_visibleRows.contains(row)) {
            m_skuData[row][2] = value;
            m_table->item(row, 4)->setText(value);
        }
    }

    updateConfigText();
    QMessageBox::information(m_resultWindow, "更新成功",
                             QString("已为 %1 个选中项更新编码").arg(selectedRows.size()));
}

void ConfigTool::onSkuItemChanged(QTableWidgetItem *item)
{
    if (m_currentImgType == "sku" && (item->column() == 3 || item->column() == 4)) {
        int row = item->row();
        int col = item->column() - 2;
        updateSkuData(row, col, item->text());
    }
}

void ConfigTool::updateSkuData(int row, int col, const QString &value)
{
    if (row >= 0 && row < m_skuData.size() && col >= 1 && col <= 2) {
        m_skuData[row][col] = value;
        updateConfigText();
    }
}

void ConfigTool::updateConfigText()
{
    QJsonObject config;
    QJsonArray mainArray, detailArray, skuArray;

    for (const QString &path : m_mainImages) {
        mainArray.append(path);
    }

    for (const QString &path : m_detailImages) {
        detailArray.append(path);
    }

    for (const QList<QVariant> &sku : m_skuData) {
        QJsonObject skuObj;
        skuObj["path"] = sku[0].toString();
        skuObj["price"] = sku[1].toString();
        skuObj["code"] = sku[2].toString();
        skuArray.append(skuObj);
    }

    config["main_images"] = mainArray;
    config["detail_images"] = detailArray;
    config["sku_images"] = skuArray;

    QJsonDocument doc(config);
    m_imageConfigText->setText(doc.toJson());
}
